//导入 createSlice 函数
import {createSlice, createAsyncThunk} from '@reduxjs/toolkit';

//1. 创建函数  用来创建异步 action              函数参数要求返回一个 promise 对象
export let asyncIncre = createAsyncThunk('zan/async_add', () => {
  return new Promise((resolve, reject) => {
    //异步操作
    setTimeout(() => {
      resolve(1);
    }, 1000);
  })
});

//创建 slice 对象
const slice = createSlice({
  name: 'zan',
  //初始值
  initialState: {
    value: 200,
    msg: ''
  },
  // 声明 reducer 的功能
  reducers: {
    // {type: 'incre', payload: 10}
    incre: (state, action) => {
      //直接修改原始状态对象中的属性
      state.value += action.payload;
    },
    // {type: 'decre', payload: 5}
    decre: (state, action) => {
      state.value -= action.payload;
    }
  },
  //2. 配置 extraReducers
  extraReducers: {
    //当异步任务成功的回调设置
    [asyncIncre.fulfilled]: (state, action) => {
      state.value += action.payload;
      state.msg = '更新成功'
    },
    [asyncIncre.rejected]: (state, action) => {
      state.msg = '更新失败'
    },
    [asyncIncre.pending]: (state, action) => {
      state.msg = '更新中'
    }
  }
});

//获得 action creator
export let {incre, decre} = slice.actions;

//暴露 reducer
export default slice.reducer;